package cn.jee.cs.controller;

import cn.jee.cs.model.College;
import cn.jee.cs.model.validation.OnCreate;
import cn.jee.cs.repo.CollegeRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/college")
@Tag(name = "college module", description = "学院管理模块")
public class CollegeController {

    @Autowired
    private CollegeRepository collegeRepository;

    //查询所有学院
    @GetMapping("/college")
    public Iterable<College> getAllColleges(){
        return collegeRepository.findAll();
    }

    @PostMapping("/college")
    @Operation(summary = "创建学院")
    public College addCollege(@Validated(OnCreate.class) @RequestBody College college){
        return collegeRepository.save(college);
    }

    @PutMapping("/college/{id}")
    @Operation(summary = "修改学院", parameters = @Parameter(name = "id",in = ParameterIn.PATH))
    public College editCollege(
            @Parameter(hidden = true) @PathVariable("id") College college,
            String name) {
        college.setName(name);
        return collegeRepository.save(college);
    }

    @DeleteMapping("/college/{id}")
    @Operation(summary = "删除学院", parameters = @Parameter(name = "id", in = ParameterIn.PATH))
    public Map<String, Object> delCollege(
            @Parameter(name = "id", hidden = true)
            @PathVariable("id") College college) {
        Map<String,Object> result = new HashMap();
        // 如果该college已经开设了很多课程，就提示用户不能删除
        if(!college.getCourses().isEmpty()) {
            result.put("success",false);
            result.put("msg","该学院还有"+ college.getCourses().size()+"门课程，请先删除对应课程");
        }else {
            collegeRepository.delete(college);
            result.put("success",true);
            result.put("msg","已经成功删除课程");
        }
        return result;
    }
}
